package com.shanghaionstar.carmanage;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.more.entity.PackageInfo;
import com.onstar.cn.more.entity.VehicleInfo;
import com.onstar.cn.more.response.DataPackageRule;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.adapter.PayMeOrderAdapter;
import com.shanghaionstar.carmanage.iview.ICarFlowPackageViewImpl;
import com.shanghaionstar.carmanage.presenter.CarFlowPackagePresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 购买安吉星套餐界面
 */
@ContentView(R.layout.car_manage_activity_buy_more_flow)
public class FlowPackageActivity extends SwipeActivity implements View.OnClickListener, PayMeOrderAdapter.Callback {

    private static final String TAG = FlowPackageActivity.class.getSimpleName();
    private WebSettings webSettings;
    private String contentUrl; //流量规则url
    @FindViewById
    ScrollView reminder_layout, rule_layout;
    @FindViewById
    LinearLayout data_ll;
    @FindViewById
    private Button buy_now_btn;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private ProgressLayout package_list_progress;
    //    @FindViewById(background = R.drawable.onstar_payme_one_year_selector)
//    private RelativeLayout one_year_layout;
    @FindViewById
    private TextView tv_CMCC, data_reminder, data_rule, textView;
    @FindViewById
    private TextView no_payme_list_data;
    @FindViewById
    private TextView package_name, actual_price, offer_desc, package_price, package_layout, duration, duration_unit;
    @FindViewById
    private WebView webView;
    @FindViewById
    private GridView elv_order_select;
    private PayMeOrderAdapter adpter;
    private List<PackageInfo> groupList;
    private List<PackageInfo> childList;
    private List<VehicleInfo> vehicleList;
    private PackageType packageType;
    @FindViewById(background = R.drawable.onstar_join_me_bg)
    private RelativeLayout layout_background;

    private CarFlowPackagePresenter packagePresenter;

    @FindViewById
    private View package_detail_ll;

    @FindViewById
    private View scroll_view;

    @Override
    public CarFlowPackagePresenter getPresenter() {
        if (packagePresenter == null) {
            packagePresenter = new CarFlowPackagePresenter(getScheduler(), this);
            attachLogicalView();
        }
        return packagePresenter;
    }

    private void attachLogicalView() {
        packagePresenter.setPackageView(new ICarFlowPackageViewImpl() {
            @Override
            public void showPackageInfos(List<PackageInfo> packageInfos) {
                FlowPackageActivity.this.showPackageInfos(packageInfos);
            }

            @Override
            public void showPackageRule(DataPackageRule packageRule) {
                FlowPackageActivity.this.showPackageRule(packageRule);
            }

            @Override
            public void showErronLoadPackageInfos(Throwable throwable) {
                FlowPackageActivity.this.showErronLoadPackageInfos(throwable);
            }

            @Override
            public void showErrOnLoadPackageRule(Throwable throwable) {
                FlowPackageActivity.this.showErrOnLoadPackageRule(throwable);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }


    private void init() {
        initView();
        initWebSetting();
        initPackageType();
        loadFlowPackageRule();
        loadFlowPackageInfos(packageType);
        registerOrderPaySuccess();
    }

    private Subscription mPaySuccessRx;

    /**
     * 支付成功关闭该页
     */
    private void registerOrderPaySuccess() {
        mPaySuccessRx = RxBus.getDefault().toObserverable(OrderPayActivity.PAY_SUCCESS, Integer.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer resp) {
                        finish();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
        RxSubscriptions.add(mPaySuccessRx);
    }

    private void initView() {
        /*温馨提示初始化数据*/
        SpannableString styledText = new SpannableString("通常1GB流量能做什么？\n" +
                "您可以查看10，000条微博，或编写20，000条微博，或收发3，750封不带附件的电子邮件，或在线收听228首标准音质歌曲，或观看443分钟标清。\n" +
                "请留意您个人设备上的系统和应用，在连接Wi-Fi时的自动更新及备份，此类后台运行将会消耗较大的数据流量。\n" +
                "\n" +
                "购买数据流量套餐\n" +
                "当您的数据流量消耗完毕或数据流量套餐过期，您将无法继续享用安吉星的4G LTE高速无线网络。您可按下蓝色安吉星按钮，或者致电安吉星服务热线 400-820-1188，客服顾问将协助您购买新的流量套餐。");
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), 12, 140, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 140, 150, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), 150, 251, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(styledText, TextView.BufferType.SPANNABLE);
        /*初始化温馨提醒indicator样式*/
        data_rule.setTextColor(getResources().getColor(R.color.vin_register_hint));
        data_reminder.setTextColor(getResources().getColor(R.color.font_flow_price));
        data_rule.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
        data_reminder.setBackgroundResource(R.drawable.img_tab);

        package_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        package_layout.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    protected void initWebSetting() {
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDisplayZoomControls(false);
    }

    private void initPackageType() {
        packageType = PackageType.DATA;
        if (getIntent().getExtras() != null) {
            packageType = (PackageType) getIntent().getExtras().getSerializable("packageType");
        }
    }

    private void loadFlowPackageRule() {
        getPresenter().getFlowPackageRule();
    }

    private void loadFlowPackageInfos(PackageType packageType) {
        tv_CMCC.setVisibility(View.VISIBLE);
        data_ll.setVisibility(View.VISIBLE);
        top_layout.setTopTitle(getString(R.string.data));
        package_list_progress.setVisibility(View.VISIBLE);
        no_payme_list_data.setVisibility(View.GONE);
        getPresenter().getFlowPackage(packageType);//获取订单信息
    }

    private void showPackageInfos(List<PackageInfo> packageInfos) {
        package_list_progress.setVisibility(View.GONE);
        groupList = packageInfos;
        if (childList == null)
            childList = new ArrayList<PackageInfo>();
        else
            childList.clear();
        if (packageType.equals(PackageType.CORE)) {
        } else {
            childList = groupList;
        }
        no_payme_list_data.setVisibility(View.GONE);
        initFlowDataPage();
    }

    private void showPackageRule(DataPackageRule packageRule) {
        if (packageRule != null)
            contentUrl = packageRule.getContentUrl();
    }

    private void showErronLoadPackageInfos(Throwable throwable) {
        if (throwable instanceof HttpException)
            AlertDialogUtil.showDialogByExceptionCode(this, (HttpException) throwable);
        no_payme_list_data.setVisibility(View.VISIBLE);
        package_list_progress.setVisibility(View.GONE);
        scroll_view.setVisibility(View.GONE);
        no_payme_list_data.setText(getResources().getString(R.string.no_payme_list_datas_error));
    }

    private void showErrOnLoadPackageRule(Throwable throwable) {
        package_list_progress.setVisibility(View.GONE);
        no_payme_list_data.setVisibility(View.VISIBLE);
        scroll_view.setVisibility(View.GONE);
        no_payme_list_data.setText(getResources().getString(R.string.no_payme_list_datas_error));
    }

    public void initFlowDataPage() {
        if (childList != null) {
            adpter = new PayMeOrderAdapter(childList, FlowPackageActivity.this, packageType, this);
            adpter.setDegreeCode(Constants.PACKAGE_HOT);
            initTabNameByList(childList);
            elv_order_select.setAdapter(adpter);
        }
    }

    private void initTabNameByList(List<PackageInfo> list) {
        if (packageType.equals(PackageType.CORE)) {
            clickTabButton();
        }
        if (packageType.equals(PackageType.DATA)) {
            clickTabButton2();
        }
    }

    //模拟点击事件 yqt
    private void clickTabButton2() {
        //t设置套餐信息
        adpter.setSelectPackInfo(childList.get(0));
        adpter.setPosition(0);
        //t设置套餐选择位置
        adpter.setSelectPosition(0);
        adpter.notifyDataSetChanged();
        package_list_progress.setVisibility(View.GONE);
    }

    private void clickTabButton() {
        if (groupList == null) {
            return;
        }
        if (childList == null) {
            childList = new ArrayList<PackageInfo>();
        } else {
            childList.clear();
        }
        for (PackageInfo entity : groupList) {
            if (!CommonUtil.isNull(entity.getDegreeCode()) && Constants.PACKAGE_HOT.equals(entity.getDegreeCode())) {
                childList.add(entity);
            }
        }
        isShowMsg(childList);
        adpter.setDegreeCode(Constants.PACKAGE_HOT);
        // t设置套餐信息，以解决 点击立即购买报“您还未选择套餐，请先选择”的问题
        adpter.setSelectPackInfo(childList.get(0));
        adpter.setPosition(0);
        adpter.setSelectPosition(0);
        adpter.notifyDataSetChanged();
    }

    @OnClick({R.id.buy_now_btn, R.id.data_reminder, R.id.data_rule})
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.buy_now_btn://立即购买
                if (adpter != null && adpter.getSelectPackInfo() != null) {
                    if (packageType == PackageType.DATA) {
//                        BusinessUtil.sendReportByClickType(FlowPackageActivity.this, FunctionNameFindId.Data_Plan_Create_Order_Button.getStringValue());
                    } else {
//                        BusinessUtil.sendReportByClickType(FlowPackageActivity.this, FunctionNameFindId.Payme_create_order.getStringValue());
                    }
                    BusinessUtil.sendReportByClickType(FlowPackageActivity.this, FunctionNameFindId.F4Gpacakge_buynow.getStringValue());
//
                    Intent intent = new Intent(this, OrderPayActivity.class);
                    intent.putExtra(OrderPayActivity.PACKAGE_TYPE, packageType);
                    intent.putExtra(OrderPayActivity.PACKAGE_PRICE, adpter.getSelectPackInfo().getActualPrice() + "");
                    intent.putExtra(OrderPayActivity.PACKAGE_NAME, adpter.getSelectPackInfo().getPackageName());
                    intent.putExtra(OrderPayActivity.PACKAGE_ID, adpter.getSelectPackInfo().getPackageId());
                    startActivity(intent);
                } else {
                    AlertDialogUtil.showAlertDialog(FlowPackageActivity.this, R.string.dialog_warning,
                            R.string.SB027_MSG013);
                }
                break;
            case R.id.data_reminder:
                BusinessUtil.sendReportByClickType(FlowPackageActivity.this, FunctionNameFindId.F4Gpackage_notes.getStringValue());
                data_rule.setTextColor(getResources().getColor(R.color.vin_register_hint));
                data_reminder.setTextColor(getResources().getColor(R.color.font_flow_price));
                data_rule.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
                data_reminder.setBackgroundResource(R.drawable.img_tab);
                rule_layout.setVisibility(View.GONE);
                reminder_layout.setVisibility(View.VISIBLE);
                break;
            case R.id.data_rule:
                BusinessUtil.sendReportByClickType(FlowPackageActivity.this, FunctionNameFindId.F4Gpackage_datarules.getStringValue());
                data_reminder.setTextColor(getResources().getColor(R.color.vin_register_hint));
                data_rule.setTextColor(getResources().getColor(R.color.font_flow_price));
                data_reminder.setBackgroundResource(R.drawable.onstar_payme_one_year_selector);
                data_rule.setBackgroundResource(R.drawable.img_tab);
                reminder_layout.setVisibility(View.GONE);
                rule_layout.setVisibility(View.VISIBLE);
                webView.loadUrl(contentUrl);
                break;
            default:
                break;
        }
    }

    public void isShowMsg(List<PackageInfo> childList) {
        if (childList.size() == 0) {
            no_payme_list_data.setVisibility(View.VISIBLE);
        } else {
            no_payme_list_data.setVisibility(View.GONE);
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mPaySuccessRx);
        top_layout = null;
    }

    /*回调函数 yongqiang tao*/
    @Override
    public void onDataClick(int p) {
        if (packageType.equals(PackageType.CORE)) {
            package_name.setText(childList.get(p).getPackageName());
//            start_date.setText(childList.get(p).getStartDate());
//            end_date.setText(childList.get(p).getEndDate());
            package_price.setText(String.valueOf(childList.get(p).getPackagePrice()));
            offer_desc.setText(childList.get(p).getOfferDesc());
            actual_price.setText(String.valueOf(childList.get(p).getActualPrice()));
        } else {
            package_name.setText(childList.get(p).getPackageName());
            duration.setText(childList.get(p).getDuration());
//            Log.i(TAG, childList.get(p).getDuration());
            if (childList != null && childList.get(p) != null) {
                sendReportByDuration(childList.get(p).getDuration());
            }
            package_price.setText(String.valueOf(childList.get(p).getPackagePrice()));
            offer_desc.setText(childList.get(p).getOfferDesc());
            actual_price.setText(String.valueOf(childList.get(p).getActualPrice()));
        }
    }

    private void sendReportByDuration(String mDuration) {
        int duration = Integer.valueOf(mDuration);
        switch (duration) {
            case 365:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpackage_oneyeardata.getStringValue());
                break;
            case 180:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpackage_halfyeardata.getStringValue());
                break;
            case 90:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpackage_quarterlydata.getStringValue());
                break;
            case 30:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.F4Gpackage_monthlydata.getStringValue());
                break;
            case 7:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.FGpackage_weeklydata.getStringValue());
                break;

        }
    }
}